package advert_api

import (
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
)

type AdvertsRequest struct {
	//structs:"title" 这是结构体快速转map引用的一个包
	Title  string `json:"title" binding:"required" structs:"title" msg:"请输入标题"`        //广告标题
	Href   string `json:"href" binding:"required,url" structs:"href"  msg:"跳转链接非法"`    //广告链接
	Images string `json:"images" binding:"required,url" structs:"images" msg:"图片地址非法"` //图片
	IsShow bool   `json:"is_show" structs:"is_show"`                                   //是否展示
}

// AdvertAddView 创建广告
// @Tags 广告管理
// @Summary 创建广告
// @Description 创建广告
// @Param data body AdvertsRequest true "表示多个参数"
// @Router /api/advert [post]
// @Produce json
// @Success 200 {object} res.Response{}
func (AdvertApi) AdvertAddView(c *gin.Context) {
	var ad AdvertsRequest
	err := c.ShouldBindJSON(&ad)
	if err != nil {
		res.FailedWithError(err, &ad, c)
		return
	}
	//根据title进行 重复判断
	var advert models.AdvertsModel
	err = global.DB.Take(&advert, "title=?", ad.Title).Error
	if err == nil {
		res.FailedWithMsg("广告已存在", c)
		return
	}
	err = global.DB.Create(&models.AdvertsModel{
		Title:  ad.Title,
		Href:   ad.Href,
		Images: ad.Images,
		IsShow: ad.IsShow,
	}).Error
	if err != nil {
		global.Log.Error(err)
		res.FailedWithMsg("添加广告失败", c)
		return
	}
	res.Ok(gin.H{
		"title":   ad.Title,
		"href":    ad.Href,
		"images":  ad.Images,
		"is_show": ad.IsShow,
	}, "添加广告成功", c)
}
